import config from '@/common/config/config.js'
import reqFilter from '@/common/config/req-filter-config.js'

const COMMONURL = config.api_base_url; //公共路径 
const LOGINURL = config.api_login_url; //登录接口
const FILEUPLOADURL = config.file_upload_url; //文件上传接口

const filter = new reqFilter(); //filter

let _this={};

export default class Https {
	constructor() {
		this.isBebug = 0; //是否开启错误检测
		_this=this;
	};

	// post请求封装
	/**
	 * 
	 * @param {请求地址} url 
	 * @param {请求的数据} requestData 
	 * @param {是否验证错误} isFilter 
	 * @param {请求类型："POST" /  "GET" 默认为 "POST" } requestType 
	 */
	Request(url, requestData = {}, isShowCenterLodin = true, isFilter = true, requestType = "GET") {
		let requestHeader = {};
		if (requestType === "POST") {
			requestHeader = {
				"content-type": "application/json",
			}
		}
		// if (uni.getStorageSync('userInfos').openid) {
		// 	try {
		// 		requestHeader.openid = uni.getStorageSync('userInfos').openid;
		// 		requestHeader.token = uni.getStorageSync('userInfos').token;
		// 	} catch (e) {

		// 	}
		// }
		let promise = new Promise((resolve, reject) => {
			if (isShowCenterLodin) {
				uni.showLoading({
					title: "正在加载~"
				})
			}
			// 请求
			uni.request({
				url: url,
				data: requestData,
				method: requestType,
				header: requestHeader,
				timeout: config.config_time_out,
				success: async res => {
					if (isFilter) {
						const err = await filter.systemCodeFilter(res.statusCode);
						if (err) return;
						const resState = await filter.resCodeFilter(res.data.code, this
							.isBebug === 3 ? {
								url: url,
								data: requestData,
								method: requestType,
								header: requestHeader,
								response: res.data
							} : null);
						// 回滚请求
						resState == 'Rollback' ? _this.Request(url, requestData, isShowCenterLodin,
							isFilter, requestType,
						) : '';
						// 未登录， 拉取收取后回滚请求
						// console.log('http this:', this);
						// console.log(_this);
						resState == 'noLogin' ? resolve(_this.wxLogin2(null, url,
							requestData,
							isShowCenterLodin,
							isFilter, requestType,
						)) : '';
					}
					const timer = setTimeout(() => {
						clearTimeout(timer);
						uni.hideLoading();
					}, 500);
					resolve(res.data);
				},
				fail: (err) => {
					const timer = setTimeout(() => {
						clearTimeout(timer);
						uni.hideLoading();
					}, 500);
					uni.showToast({
						title: "连接超时~",
						icon: "none",
						duration: 2000
					})
				}
			});
		});
		return promise;
	}
	/**
	 * 微信授权登录
	 * 
	 */
	logins() {
		uni.showLoading({
			title: "正在登陆中！！！"
		});
		let promis = new Promise((resolve, reject) => {
			uni.login({
				provider: 'weixin',
				success: res2 => {
					resolve(res2);
				},
				fail: () => {
					uni.showToast({
						title: '微信登录授权失败',
						icon: 'none'
					});
					return;
				},
				complete() {
					uni.hideLoading();
				}
			});
		}).then(res => {
			return new Promise(resolve => {
				uni.getUserInfo({
					provider: 'weixin',
					success: info => {
						//这里请求接口
						// console.log(info);
						let authorizeInfos = info.userInfo;
						authorizeInfos.jscode = res.code;
						resolve(authorizeInfos);
					},
					fail: () => {
						uni.showToast({
							title: '微信登录授权失败',
							icon: 'none'
						});
						return;
					},
					complete() {
						uni.hideLoading();
					}
				});
			})

		}).then(res => {
			return new Promise(resolve => {
				uni.request({
					method: "POST",
					url: COMMONURL + LOGINURL,
					data: {
						js_code: res.jscode,
						nickname: res.nickName,
						avatar: res.avatarUrl,
						gender: res.gender,
						country: res.country,
						province: res.province,
						city: res.city,
						language: res.language
					},
					success: (ress) => {
						if (ress.data.code === 200) {
							// 登陆成功
							uni.setStorageSync('userInfos', ress.data.data);
							uni.showToast({
								title: "授权成功！！",
								icon: "none",
								success() {
									// console.log("授权成功！！");
									resolve("1");
								}
							})
						} else {
							// 登陆失败，清除授权信息
							uni.showToast({
								title: ress.msg,
								icon: 'none',
								success() {
									resolve("0");
								}
							});
						}
					},
					complete(ress) {
						uni.hideLoading();
					}
				})
			})
		});
		return promis;
	}
	// 微信登录2
	wxLogin2(pid, ...option) {
		uni.showLoading({
			title: "正在登陆中..."
		});
		let promis = new Promise(resolve => {
			// 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
			// 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
			wx.getUserProfile({
				desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
				success: (res) => {
					resolve(res);
				},
				fail: err => {
					uni.hideLoading();
					console.log(err);
					if (err.errMsg.indexOf('can only be invoked by user TAP gesture')>=0) {
						uni.showModal({
							content: '您还未登录，是否立即去登录？',
							success: (e) => {
								if (e.confirm) {
									uni.switchTab({
										url: '/pages/tabbers/my'
									})
								}
							}
						});
						return;
					}
					uni.showToast({
						title: '微信登录授权失败',
						icon: 'none'
					});
				}
			})
		}).then(res => {
			return new Promise(resolve => {
				uni.login({
					provider: 'weixin',
					success: res2 => {
						res2.info = res;
						resolve(res2);
					},
					fail() {
						uni.hideLoading();
					}
				});
			})
		}).then(res => {
			const uInfo = res.info.userInfo;
			return new Promise(async resolve => {
				const url = LOGINURL;
				const datas = {
					js_code: res.code,
					nickname: uInfo.nickName,
					avatar: uInfo.avatarUrl,
					gender: uInfo.gender,
					country: uInfo.country,
					province: uInfo.province,
					city: uInfo.city,
					language: uInfo.language,
					pid: pid ? pid : null
				};

				let response = await this.Request(url, datas);
				console.log(response);
				if (response.code === 1) {
					uni.setStorageSync('userInfos', response.data);
					if (option.length > 0) {
						// 回滚
						resolve(this.Request(...option));
					}
					uni.showToast({
						title: "登录成功！",
						icon: "none"
					});
					resolve(response.data);
				} else {
					uni.showToast({
						title: "登录失败 请稍后再试",
						icon: "none"
					});
					resolve(null);
				}
			})
		})
		return promis;
	}

	/**
	 * 文件上传
	 * @param {Object} path  文件路径
	 */
	uploadFiles(path) {
		return new Promise(resolve => {
			const uploadTask = uni.uploadFile({
				url: COMMONURL + FILEUPLOADURL, //仅为示例，非真实的接口地址
				filePath: path,
				name: 'file',
				header: {
					"content-type": "multipart/form-data",
				},
				formData: {
					path: 'goods'
				},
				success: uploadFileRes => {
					let res = JSON.parse(uploadFileRes.data);
					resolve(res.data);
				}
			});
			uploadTask.onProgressUpdate(res => {
				let showInfo = '';
				if (res.progress <= 3) {
					showInfo = '开始上传';
				} else if (res.progress > 3 && res.progress < 98) {
					showInfo = `已上传${res.progress}%`;
				} else {
					showInfo = `即将完成`;
				}
				uni.showLoading({
					title: showInfo
				});
				if (res.progress === 100) {
					let timer = setTimeout(() => {
						uni.hideLoading();
						uni.showToast({
							title: "上传成功"
						});
						clearTimeout(timer);
					}, 1000);
				}
			});
		})
	}
	/**
	 * 上传图片
	 */
	uploadImg(uploadMaxNum, sourceType = ['camera', 'album']) {
		return new Promise(resolve => {
			uni.chooseImage({
				count: uploadMaxNum, //默认9
				sourceType: sourceType,
				success: async chooseImageRes => {
					const tempFilePaths = chooseImageRes.tempFilePaths;
					let imgArr = [],
						i = 0
					for (i; i < tempFilePaths.length; i++) {
						let res = await this.uploadFiles(tempFilePaths[i]);
						imgArr.push(res);
					}
					resolve(imgArr);
				}
			});
		})
	}
	// 更改bebug状态
	updateIsBebug() {
		++this.isBebug;
		if (this.isBebug === 3) {
			uni.showToast({
				title: "已成功开启异常检测模式！",
				icon: "none",
				duration: 2500
			});
		} else if (this.isBebug > 3) {
			this.isBebug = 0;
		}
	}
}
